<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->load->helper(array('form', 'url'));
        $this->load->library(array('session'));
        $this->load->database();

        $this->load->model('admin_model');
        //调试模式
        //$this->output->enable_profiler(TRUE);
    }

    public function index()
    {
        if(islogin() == true){jump('/admin/Blog','您已登录');return;}

        //定义网页相关数据
        $data['title'] = 'Li Lijie - 后台登录';
        $data['name'] = empty($_SESSION['check']) == 1 ? '' : $_COOKIE['name'];
        $data['psw'] = empty($_SESSION['check']) == 1 ? '' : $_COOKIE['psw'];
        $this->load->view('admin/login',$data);
        $this->load->view('admin/footer');
    }

    /**
     * 登录
     */
    public function in()
    {
        if(islogin() == true){jump('/admin/Blog','您已登录');return;}

        if(!isset($_POST))
            jump('/admin/editblog','表单为空');

        //获取表单信息
        $data = array(
            'name' => $this->input->post('name'),  //名字
            'psw' => $this->input->post('psw'),  //密码
            'check' => $this->input->post('check')  //remember
        );

        //验证码验证失败
        if($this->input->post('code') != $_SESSION['code']){
            back('验证码错误');
            return;
        }

        if ($this->admin_model->login($data['name'],$data['psw'])) {
            $_SESSION['name'] = $data['name'];
            $_SESSION['check'] = '';
            //选择记住密码
            if(!empty($data['check'])){
                setcookie('name',$data['name']);
                setcookie('psw',$data['psw']);
                $_SESSION['check'] = $data['check'];
            }
            jump('/admin/blog','登录成功');
            return;
        }
        else
            jump('/admin/login','账号或密码错误');
    }

    /**
     * 登出
     */
    public function out()
    {
        //删除session
        if(isset($_SESSION['name'])){
            unset($_SESSION['name']);
            unset($_SESSION['check']);
            $msg = '您已登出';
        }
        else
            $msg = '您尚未登录';
        jump('/admin/login',$msg);
    }

    /**
     * 产生验证码
     */
    public function code(){
        $config = array(
            'height' => '35',
            'size' =>'20',
            'name' => 'code'
        );
        $this->load->library('code',$config);
        $this->code->show();
    }
}